<template>
  <el-dialog v-model="dialogVisible" style="max-height: 850px; overflow-y: auto;" title="事故详情" width="50%" :close-on-click-modal="false" @close="close">
    <el-descriptions :column="1" border>
      <el-descriptions-item label="事故编号">{{
        detailData.sgbh
      }}</el-descriptions-item>
      <el-descriptions-item label="行政区划">{{
        detailData.xzqh
      }}</el-descriptions-item>
      <el-descriptions-item label="登记编号">{{
        detailData.djbh
      }}</el-descriptions-item>
      <el-descriptions-item label="发生时间">{{
        detailData.sgfssj
      }}</el-descriptions-item>
      <el-descriptions-item label="路号">{{
        detailData.lh
      }}</el-descriptions-item>
      <el-descriptions-item label="路名">{{
        detailData.lm
      }}</el-descriptions-item>
      <el-descriptions-item label="公里数">{{
        detailData.gls !== null ? detailData.gls : "无数据"
      }}</el-descriptions-item>
      <el-descriptions-item label="米数">{{
        detailData.ms
      }}</el-descriptions-item>
      <el-descriptions-item label="事故地点">{{
        detailData.sgdd
      }}</el-descriptions-item>
      <el-descriptions-item label="受伤人数">{{
        detailData.ssrs
      }}</el-descriptions-item>
      <el-descriptions-item label="死亡人数">{{
        detailData.swrs
      }}</el-descriptions-item>
      <el-descriptions-item label="简要案情">{{
        detailData.jyaq
      }}</el-descriptions-item>
      <el-descriptions-item label="事故初始原因">{{
        detailData.sgccyy
      }}</el-descriptions-item>
      <el-descriptions-item label="事故认定原因">{{
        detailData.sgrdyy !== null ? detailData.sgrdyy : "无数据"
      }}</el-descriptions-item>
      <el-descriptions-item label="坐标">{{
        detailData.dzzb
      }}</el-descriptions-item>
      <el-descriptions-item label="道路隔离设施">{{
        detailData.dlwlgl
      }}</el-descriptions-item>
      <el-descriptions-item label="中央隔离设施">{{
        detailData.zyglss
      }}</el-descriptions-item>
      <el-descriptions-item label="路侧防护设施">{{
        detailData.fhss
      }}</el-descriptions-item>
      <el-descriptions-item label="路面情况">{{
        detailData.lmzk
      }}</el-descriptions-item>
      <el-descriptions-item label="路表情况">{{
        detailData.lbqk
      }}</el-descriptions-item>
      <el-descriptions-item label="照明条件">{{
        detailData.zmtj
      }}</el-descriptions-item>
    </el-descriptions>
    <div>
      <div>
        <h3 class="color-white mb-10px">事故地点情况</h3>
        <div v-if="detailData.imageList && detailData.imageList.length > 0"
          class="flex items-center flex-wrap gap-8px mb-10px">
          <img @click="handlePictureCardPreview(detailData.imageList, 'wholeUrl')"
            v-for="(item, idx) in detailData.imageList" :key="idx" :src="item?.wholeUrl" class="w-3 h-3" alt="事故图片" />
        </div>
        <div v-else class="mb-10px text-gray-400">
          暂无事故地点图片
        </div>
      </div>
      <h3 class="color-white mb-10px">提交图片</h3>
      <el-upload action="#" list-type="picture-card" :auto-upload="false" :on-change="handleOnPictureChange"
        :file-list="uploadedFiles" :on-remove="handleRemove" :on-success="handleSuccess"
        :on-preview="handlePictureCardPreview">
        <el-icon>
          <Plus />
        </el-icon>

        <template #file="{ file }">
          <div>
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(uploadedFiles)">
                <el-icon>
                  <ZoomIn />
                </el-icon>
              </span>
              <span v-if="!disabledPicture" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <el-icon>
                  <Delete />
                </el-icon>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
      <el-button type="primary" @click="uploadPictures" class="mt-10px">提交</el-button>
    </div>
  </el-dialog>

  <el-image-viewer v-if="pictureVisible" :url-list="dialogImageUrl" show-progress @close="pictureVisible = false" />
  <!-- <el-dialog width="50%" append-to-body v-model="pictureVisible">
    <img class="w-full h-800px" :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog> -->
</template>

<script lang="ts" setup>
import { AccidentDetails } from "@/service/api/map"; // 假设接口文件在该路径下
import * as MapApi from "@/service/api/map";
import type { UploadFile, UploadFiles } from "element-plus";
interface Accident {
  sgbh: string; //事故编号
  xzqh: string; //行政区划
  djbh: string; //登记编号
  sgfssj: string; //事故发生时间
  lh: string; //路号
  lm: string; //路名
  gls: string | null; //公里数
  ms: string; //米数
  sgdd: string; //事故地点
  ssrs: string; //受伤人数
  swrs: string; //死亡人数
  jyaq: string; //简要案情
  sgccyy: string; //事故初始原因
  sgrdyy: string; //事故认定原因
  dzzb: string; //经纬度
  dlwlgl: string; //道路隔离设施
  zyglss: string; //中央隔离设施
  fhss: string; //路面防护设施
  lmzk: string; //路面情况
  lbqk: string; //路表情况
  zmtj: string; //照明条件
  imageList: Array<{ wholeUrl: string }> | null;
}

const dialogVisible = ref(false);
const emit = defineEmits(["close"]);
const detailData = ref<Accident>({} as Accident);
const uploadedFiles = ref<UploadFile[]>([]);
const disabledPicture = ref(false);
const pictureVisible = ref(false);
const dialogImageUrl = ref<any>([]);
const currentDetail = ref<any>({});
const accidentDetailId = ref("");
// const fileList = ref<UploadFile[]>([]);
const message = useMessage();
const sgbh = ref("");
const params = ref<any>({
  sgbh: "",
  imageList: [],
});
const uploadPictures = async () => {
  try {
    params.value.sgbh = sgbh.value;
    if (detailData.value.imageList) {
      params.value.imageList.push(...detailData.value.imageList);
    }
    await MapApi.PostSave(params.value);
    message.success("保存成功");
    reset();
    await fetchAccidentDetails(accidentDetailId.value);
  } catch (err) {
    console.log(err);
  }
};
const handleOnPictureChange = async (
  file: UploadFile,
  uploadFiles: UploadFiles
) => {
  uploadedFiles.value = uploadFiles;

  if (file.status === "success" || file.status === "fail") {
    return;
  }

  const loading = message.loading("图片上传中...");

  try {
    if (!file.raw) {
      throw new Error("文件无效");
    }

    const formData = new FormData();
    formData.append("file", file.raw, file.name);

    if (currentDetail.value?.id) {
      formData.append("accidentId", currentDetail.value.id.toString());
    }
    const res = await MapApi.PostAccidentHeatpictur(formData);

    if (!res || !res.wholeUrl) {
      throw new Error(res?.msg || "上传失败，服务器未返回有效图片地址");
      return;
    }
    const uploadedFileItem = uploadedFiles.value.find(
      (item) => item.uid === file.uid
    );
    if (uploadedFileItem) {
      uploadedFileItem.status = "success";
      uploadedFileItem.url = res.wholeUrl;
      uploadedFileItem.response = res;
    } else {
      console.warn("上传成功后未找到对应文件项，这可能导致显示问题。");
      file.url = res.wholeUrl;
      file.status = "success";
    }
    params.value.imageList.push(res);
    message.success("图片上传成功");
  } catch (err: any) {
    console.error("上传错误:", err);
    const uploadedFileItem = uploadedFiles.value.find(
      (item) => item.uid === file.uid
    );
    if (uploadedFileItem) {
      uploadedFileItem.status = "fail";
    } else {
      file.status = "fail";
    }
    message.error(err.message || "图片上传失败");
  } finally {
    loading.close();
  }
};

const handleRemove = async (file: UploadFile) => {
  const indexToDelete = uploadedFiles.value.findIndex(
    (item) => item.uid === file.uid
  );

  if (indexToDelete !== -1) {
    // 从 uploadedFiles.value 中移除文件，并更新响应式数据
    const newUploadedFiles = uploadedFiles.value.filter(
      (item) => item.uid !== file.uid
    );
    uploadedFiles.value = newUploadedFiles;
    params.value.imageList.splice(indexToDelete, 1);

    message.info("图片已从列表中移除");
  } else {
    console.warn("未能在 uploadedFiles.value 中找到要删除的文件:", file);
    message.warning("未能找到要删除的图片，请检查。");
  }
};
const handleSuccess = (response: any, uploadFile: UploadFile) => {
  const uploadedFileItem = uploadedFiles.value.find(
    (item) => item.uid === uploadFile.uid
  );
  if (uploadedFileItem) {
    uploadedFileItem.url = response.url || response.wholeUrl;
    uploadedFileItem.status = "success";
  }
  message.success("图片上传成功");
};
const handlePictureCardPreview = (files, type = '') => {
  dialogImageUrl.value=[];
  if (type === 'wholeUrl') {
    files.map(item => {
      item.url = item.wholeUrl
    })
  }

  files.map(item =>{
    dialogImageUrl.value.push(item.url)
  })
  pictureVisible.value = true;
};
const fetchAccidentDetails = async (id) => {
  try {
    accidentDetailId.value = id;
    const response = await AccidentDetails(id);
    if (response) {
      detailData.value = response;
      dialogVisible.value = true;
    }
  } catch (error) {
    console.error("Error fetching accident details:", error);
  }
};

const close = () => {
  dialogVisible.value = false;
  accidentDetailId.value = '';
  reset();
  emit("close");
};

const reset = () => {
  uploadedFiles.value = [];
  params.value.imageList = [];
  detailData.value = {} as Accident;
}

defineExpose({ fetchAccidentDetails, sgbh });
</script>

<style lang="less" scoped>
/* 样式可以根据需要调整 */
::v-deep .el-descriptions__body .el-descriptions__table.is-bordered .el-descriptions__cell {
  background: transparent !important;
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.7) !important;
  min-width: 100px;
  text-align: center;
}

::v-deep .el-descriptions__body {
  max-height: 330px;
  overflow-y: scroll;
}

::v-deep .el-descriptions__body::-webkit-scrollbar {
  width: 0;
}

::v-deep .el-descriptions__body {
  background-color: transparent !important;
}
</style>
